package com.nbcio.pm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nbcio.common.mybatis.core.page.PageQuery;
import com.nbcio.common.mybatis.core.page.TableDataInfo;
import com.nbcio.common.core.utils.MapstructUtils;
import com.nbcio.common.core.utils.StringUtils;
import com.nbcio.pm.domain.PmTeamRole;
import com.nbcio.pm.domain.bo.PmTeamRoleBo;
import com.nbcio.pm.domain.vo.PmTeamRoleVo;
import com.nbcio.pm.mapper.PmTeamRoleMapper;
import com.nbcio.pm.service.IPmTeamRoleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 团队角色Service业务层处理
 *
 * @author nbacheng
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class PmTeamRoleServiceImpl implements IPmTeamRoleService {

    private final PmTeamRoleMapper baseMapper;

    /**
     * 查询团队角色
     */
    @Override
    public PmTeamRoleVo queryById(Long roleId) {
        return baseMapper.selectVoById(roleId);
    }

    /**
     * 查询团队角色列表
     */
    @Override
    public TableDataInfo<PmTeamRoleVo> queryPageList(PmTeamRoleBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<PmTeamRole> lqw = buildQueryWrapper(bo);
        Page<PmTeamRoleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询团队角色列表
     */
    @Override
    public List<PmTeamRoleVo> queryList(PmTeamRoleBo bo) {
        LambdaQueryWrapper<PmTeamRole> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<PmTeamRole> buildQueryWrapper(PmTeamRoleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<PmTeamRole> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getRoleName()), PmTeamRole::getRoleName, bo.getRoleName());
        lqw.eq(StringUtils.isNotBlank(bo.getRoleCode()), PmTeamRole::getRoleCode, bo.getRoleCode());
        lqw.eq(bo.getRoleLevel() != null, PmTeamRole::getRoleLevel, bo.getRoleLevel());
        lqw.eq(StringUtils.isNotBlank(bo.getIsSystem()), PmTeamRole::getIsSystem, bo.getIsSystem());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), PmTeamRole::getStatus, bo.getStatus());
        lqw.orderByAsc(PmTeamRole::getSortOrder);
        return lqw;
    }

    /**
     * 新增团队角色
     */
    @Override
    public Boolean insertByBo(PmTeamRoleBo bo) {
        PmTeamRole add = MapstructUtils.convert(bo, PmTeamRole.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setRoleId(add.getRoleId());
        }
        return flag;
    }

    /**
     * 修改团队角色
     */
    @Override
    public Boolean updateByBo(PmTeamRoleBo bo) {
        PmTeamRole update = MapstructUtils.convert(bo, PmTeamRole.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(PmTeamRole entity) {
        // 校验角色编码唯一性
        LambdaQueryWrapper<PmTeamRole> lqw = Wrappers.lambdaQuery();
        lqw.eq(PmTeamRole::getRoleCode, entity.getRoleCode());
        lqw.ne(entity.getRoleId() != null, PmTeamRole::getRoleId, entity.getRoleId());
        if (baseMapper.exists(lqw)) {
            throw new RuntimeException("角色编码已存在");
        }
    }

    /**
     * 批量删除团队角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            // 校验角色是否被使用
            // TODO: 添加角色使用情况校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据角色编码查询角色
     */
    @Override
    public PmTeamRoleVo queryByRoleCode(String roleCode) {
        return baseMapper.selectPmTeamRoleByCode(roleCode, "000000");
    }

    /**
     * 查询用户拥有的角色列表
     */
    @Override
    public List<PmTeamRoleVo> queryRolesByUserId(Long userId) {
        return baseMapper.selectRolesByUserId(userId, "000000");
    }

    /**
     * 分配角色权限
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean assignRolePermissions(Long roleId, List<Long> permissionIds) {
        try {
            // 1. 删除该角色的所有权限关联
            baseMapper.deleteRolePermissions(roleId, "000000");
            
            // 2. 插入新的权限关联
            if (permissionIds != null && !permissionIds.isEmpty()) {
                for (Long permissionId : permissionIds) {
                    baseMapper.insertRolePermission(roleId, permissionId, "000000");
                }
            }
            
            return true;
        } catch (Exception e) {
            throw new RuntimeException("分配角色权限失败: " + e.getMessage(), e);
        }
    }

    /**
     * 查询角色权限列表
     */
    @Override
    public List<Long> queryRolePermissionIds(Long roleId) {
        // 使用Mapper方法查询角色权限ID列表
        return baseMapper.selectRolePermissionIds(roleId, "000000");
    }
}
